package com.qfedu.fmmall.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.fmmall.config.ObjectMapperUtil;
import com.qfedu.fmmall.entity.*;
import com.qfedu.fmmall.mapper.CategoryMapper;
import com.qfedu.fmmall.mapper.ProductImgMapper;
import com.qfedu.fmmall.mapper.ProductMapper;
import com.qfedu.fmmall.service.CategoryService;
import com.qfedu.fmmall.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductImgMapper productImgMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResultVO listpage() {
//        从缓存获取三级分类
        String categoryVO = stringRedisTemplate.opsForValue().get("CategoryVO");
        if (categoryVO != null) {
            try {
                ArrayList arrayList = ObjectMapperUtil.getObjectMapper().readValue(categoryVO, ArrayList.class);
                return ResultVO.success(arrayList, "成功！");
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        } else {
//            没有从数据库查询
            List<CategoryVO> list = categoryMapper.listpage();
            List<CategoryVO> list2 = new ArrayList<>();
            Map<Integer, CategoryVO> map = new HashMap<>();
            list.forEach(item -> {
                map.put(item.getCategoryId(), item);
                if (item.getParentId() == 0) {
                    list2.add(item);
                }
                CategoryVO vo = map.get(item.getParentId());
                if (vo != null) {
                    if (vo.getCategories() == null) {
                        vo.setCategories(new ArrayList<>());
                    }
                    vo.getCategories().add(item);
                }
            });
            try {
//                保存到缓存中，并设置过期时间为一天
                stringRedisTemplate.opsForValue().set("CategoryVO", ObjectMapperUtil.getObjectMapper().writeValueAsString(list2));
                stringRedisTemplate.expire("CategoryVO", 1, TimeUnit.DAYS);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            return ResultVO.success(list2, "成功！");
        }
    }
    /**
     * 分类推荐商品接口
     * @return
     */
    @Override
    public ResultVO recommends() {
        List<Category> list = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getCategoryLevel, 1));
        List<CategoryVO> list2=new ArrayList<>();
        list.forEach(item->{
           Page<Product> page=new Page(0,6);
           LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<Product>();
           queryWrapper.eq(Product::getRootCategoryId,item.getCategoryId());
           queryWrapper.orderByDesc(Product::getSoldNum);
             productMapper.selectPage(page, queryWrapper);
            CategoryVO vo=new CategoryVO();
            BeanUtils.copyProperties(item, vo);
            if (vo.getProducts()==null) {
                vo.setProducts(new ArrayList<>());
            }
             for (Product product: page.getRecords()) {
                 List<ProductImg> imgs = productImgMapper.selectList(new LambdaQueryWrapper<ProductImg>().eq(ProductImg::getItemId, product.getProductId()));
                 ProductVO vo1=new ProductVO();
                 BeanUtils.copyProperties(product,vo1);
                 if (vo1.getImgs()==null) {
                     vo1.setImgs(new ArrayList<>());
                 }
                 vo1.setImgs(imgs);
                 vo.getProducts().add(vo1);
             }

             list2.add(vo);
        });
        return ResultVO.success(list2,"111111");
    }
}
